// pages/citySearch/myCity/myCity.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        cityArr: [],
        loadingOver: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.getMyCity()
    },

    // 获取我的城市
    getMyCity() {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'cjMap/getCityByUid',
            data: {
                authId: app.globalData.authId
            },
            success(res) {
                if (res.data.status === '0') {
                    // 定义一个暂时的空数组
                    let tempRecordCity = [];
                    tempRecordCity = res.data.data;
                    tempRecordCity.forEach(item => {
                        if (item.enname) {
                            item.foreignName = item.enname && (item.enname.split(',')[2] || item.enname.split(',')[1])
                        }
                    })
                    _that.setData({
                        cityArr: tempRecordCity,
                        loadingOver: true
                    })
                }
            }
        })
    },


    goToIndex(e) {
        let _that = this;

        let country = e.currentTarget.dataset.country;
        let city = e.currentTarget.dataset.city;

        let lng = e.currentTarget.dataset.lng;
        let lat = e.currentTarget.dataset.lat;
        // 有些城市后台暂时没有经纬度
        if (lng && lat) {
            // 修改全局变量
            app.globalData.countryBack = country;
            app.globalData.addressBack = city;
            app.globalData.cityLat = lat;
            app.globalData.cityLng = lng;

            // 创建历史记录
            _that.createCitySearchHistory(app.globalData.authId, city, country);

            let pages = getCurrentPages(); //当前页面栈
            let prevPage = pages[pages.length - 3]; //上上一页面（地图首页）
            prevPage.setData({
                //直接给index页面赋值
                mapLongitude: lng,
                mapLatitude: lat,
                mapScale: 12,
            });
            wx.switchTab({
                url: '../../index/index',
            });
        } else {
            wx.showModal({
                title: '位置获取失败',
                content: '当前城市暂未覆盖，请联系后台管理员',
                showCancel: false
            })
        }

    },

    // 创建历史记录
    createCitySearchHistory(authId, city, country) {
        wx.request({
            url: app.globalData.rootPath + 'cjMap/createCitySearchHistory',
            data: {
                authId,
                city,
                country
            },
            success(res) {
                console.log(res);
            }
        })
    },
})